from typing import List
from fastapi import APIRouter, Depends, status, Response
from db import get_db, crud
from schemas.config import UpdateConfigRequest, ConfigModel, TodayRecommendItem, HomeRecommendItem
from schemas.flower import FlowerModel
from schemas.users import UserModel
from users.users import verify_token
from utils.response import HTTPException
from sqlalchemy.orm import Session
from datetime import datetime

router = APIRouter(prefix="/config", tags=["应用配置"])


@router.get("", response_model=ConfigModel, response_model_exclude_none=True)
def get_config(name: str, db: Session = Depends(get_db)):
    return crud.Config.get_by_name(db, name)


@router.put("", dependencies=[Depends(verify_token)], response_model_exclude_none=True)
def update_config(data: UpdateConfigRequest, user: UserModel = Depends(verify_token), db: Session = Depends(get_db)):
    data.updated_on = datetime.now()
    data.updated_by = user.id
    crud.Config.update(db, data)

    return Response()


@router.get("/weixin-today-recommend", response_model=List[TodayRecommendItem], response_model_exclude_none=True)
def get_weixin_today_recommend(db: Session = Depends(get_db)):
    recommend = crud.Config.get_by_name(db, "weixin-today-recommend")
    if recommend is None:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    result: List[TodayRecommendItem] = []

    for i in recommend.data:
        flower = crud.Flower.get(db, i["flower_id"])
        if flower is not None:
            result.append(TodayRecommendItem(
                **i,
                flower=FlowerModel.from_orm(flower)
            ))

    return result


@router.get("/weixin-home-recommend", response_model=List[HomeRecommendItem], response_model_exclude_none=True)
def get_weixin_home_recommend(db: Session = Depends(get_db)):
    recommend = crud.Config.get_by_name(db, "weixin-home-recommend")
    if recommend is None:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    result: List[HomeRecommendItem] = []

    for i in recommend.data:
        flower_list: List[FlowerModel] = []

        for j in i["children"]:
            flower = crud.Flower.get(db, j)
            if flower is not None:
                flower_list.append(FlowerModel.from_orm(flower))

        result.append(HomeRecommendItem(
            id=i["id"],
            title=i["title"],
            children=flower_list
        ))

    return result
